<template>
  <div class="img-list" ref="imgListRef">
    <!-- 默认展示第一张图片 -->
    <img
      class="img"
      v-for="(item, index) in imgList"
      :key="index"
      :src="imgList[0]"
      :data-src="item"
      alt="about" />
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';

// 使用 import.meta.glob 动态导入图片并明确类型
const images = import.meta.glob('@/assets/images/*.jpeg', {
  eager: true,
  import: 'default',
}) as Record<string, string>; // 确保类型是 Record<string, string>

const imgList = ref<string[]>([]);

// 将导入的图片路径提取出来
for (const path in images) {
  imgList.value.push(images[path]); // 直接使用路径
}

// 监听图片是否进入可视区域，如果进入可视区域则加载图片
const imgListRef = ref<HTMLElement | null>(null);
onMounted(() => {
  if (!imgListRef.value) return;

  const io = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        const img = entry.target as HTMLImageElement;
        img.src = img.dataset.src!;
      }
    });
  });

  for (let i = 0; i < imgListRef.value.children.length; i++) {
    const img = imgListRef.value.children[i] as HTMLImageElement;
    io.observe(img);
  }
});
</script>

<style scoped lang="scss">
.img-list {
  width: 640px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
  .img {
    width: 200px;
    height: 200px;
    object-fit: cover;
    border-radius: 20px;
  }
  .img:hover {
    transform: scale(1.1);
    transition: all 0.3s ease;
  }
  .img:not(:hover) {
    transform: scale(1);
    transition: all 0.3s ease;
  }
}
</style>
